package com.rz.core.handler;


import com.rz.core.exception.GlobalException;
import com.rz.core.kit.RespKit;
import com.rz.core.resp.ResultResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * author: Rui.Zhou
 * date: 2018/7/17
 * Description:
 */
@ControllerAdvice
public class ExHandler {
    private Logger logger = LoggerFactory.getLogger(ExHandler.class);
    /**
     * @ExceptionHandler(value = Exception.class):声明要捕获的异常类
     */
    @ExceptionHandler(value= Exception.class)
    @ResponseBody
    public ResultResp handle(Exception e) {
        e.printStackTrace();
        if (e instanceof GlobalException) {
            GlobalException globalException = (GlobalException) e;
            return RespKit.error(null, globalException.getMessage());
        } else {
            logger.error("异常信息：{},{}",e.getMessage(), e);
            if(e.getCause()!=null){
                return RespKit.error(null,buildErrorMsg(e.getCause().getMessage()));
            }else{
                return RespKit.error(null,buildErrorMsg(e.getMessage()));
            }
        }
    }

    private String buildErrorMsg(String message){
        if(!StringUtils.isEmpty(message)){
            int index = message.indexOf("Duplicate entry");
            if(index != -1){
                String msg = message.replaceAll("Duplicate entry","保存错误：值 ");
                return msg.replaceAll("for key","重复在字段：");
            }
        }
        return message;
    }
}